import hashlib

import requests
from lxml import etree




def prase_url(html,format):
    sel = etree.HTML(html)
    res = sel.xpath(format)
    return res

# 得到sha1值
def sha1(txt):
    sha = hashlib.sha1()
    sha.update(txt.encode('utf8'))
    result = sha.hexdigest()
    return result
def meta_data(html):
    other_msg = {
        # "uid_name" : "",
        "specimen_id": "",
        "MetaData": "",
        "iterm_type": "",
        "genus": "",
        "species": ""
    }
    format_metadata = "//div[@class='ep_summary_content_right']/h3//text()"
    format_type = "//div[@class='ep_summary_content_left']/div[1]/span[@class='md_d']/text()"
    format_genus = "//div[@class='ep_summary_content_left']/div[2]/span[@class='md_d']/a/text()"
    format_Species = "//div[@class='ep_summary_content_left']/div[3]/span[@class='md_d']/text()"
    format_uname = "//div[@class='ep_summary_content_right']/h3/em/span[@id='title']/span/text()"
    format_specimen_id = "//div[@class='ep_summary_content_right']/h3/text()[1]"
    # html = requests.get("https://linnean-online.org/170239/").text
    try:
        s = prase_url(html,format_metadata)
        price = [x.strip() for x in s if x.strip() != '']
        MetaData = " ".join(price)
    except Exception as e:
        MetaData = ''
    try:
        iterm_type = prase_url(html,format_type)[0].strip()
    except Exception as e:
        iterm_type = ''
    try:
        genus = prase_url(html,format_genus)[0]
    except Exception as e:
        genus = ''
    try:
        species = prase_url(html,format_Species)[0].strip()
    except Exception as e:
        species = ''
    try:
        specimen_id = prase_url(html,format_specimen_id)[0].strip()
    except Exception as e:
        specimen_id = ''

    other_msg["specimen_id"] = specimen_id
    other_msg["MetaData"] = MetaData
    other_msg["iterm_type"] = iterm_type
    other_msg["genus"] = genus
    other_msg["species"] = species
    return other_msg


# 获取物种uid
# def get_uid(species,name):
#     base_url_plant = 'https://cms-plant.glority.cn/web/info/query_species?classification=Plant&q={}'
#     base_url_animal ='https://cms-insect.glority.cn/web/info/query_species?classification={}&q={}'
#     if species=='linnean=5Fherbarium/' or species=='smith=5Fherbarium/':
#         url = base_url_plant.format(name)
#         res = base_craw(url,'','')
#         res_json = json.loads(res.text)
#         if res_json['items']["status"] == 0:
#             uid = res_json['items']["uid"]
#             print(uid)
#             return uid
#         elif res_json['items']["status"] == 1001 or res_json['items']["status"] == 1002:
#             url = base_url_animal.format('Mushroom',name)
#             res = base_craw(url, '', '')
#             uid = res_json['items']["uid"]
#             print(uid)
#             return uid
#         else:
#             pass

# get_uid('linnean=5Fherbarium/')

